/*
 * Copyright 2022 The TensorFlow Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.hanguangfacsemoanaapp

import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import androidx.navigation.Navigation.findNavController
import com.example.hanguangfacsemoanaapp.databinding.ActivityMainBinding
import com.google.zxing.integration.android.IntentIntegrator
import com.journeyapps.barcodescanner.CaptureActivity

/**
 * Main entry point into our app. This app follows the single-activity pattern, and all
 * functionality is implemented in the form of fragments.
 */
class MainActivity : AppCompatActivity() {

    private lateinit var activityMainBinding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityMainBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(activityMainBinding.root)
        activityMainBinding.settingsButton.setOnClickListener{showSetServerHostDialog()}
        activityMainBinding.btnScanQr.setOnClickListener{onScanQR()}
    }

    fun onScanQR(){

        // 初始化扫描器
        val integrator = IntentIntegrator(this)
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
//        integrator.setPrompt("请扫描二维码")
        integrator.setCameraId(1)  // Use a specific camera of the device
        integrator.setBeepEnabled(true)
        integrator.setOrientationLocked(false)

        integrator.setCaptureActivity(CaptureActivity::class.java)

        integrator.initiateScan()
//        val navController = findNavController(activityMainBinding.fragmentContainer)
//        navController.navigate(R.id.action_camera_to_qr)
    }

    override fun onBackPressed() {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
            // Workaround for Android Q memory leak issue in IRequestFinishCallback$Stub.
            // (https://issuetracker.google.com/issues/139738913)
            finishAfterTransition()
        } else {
            super.onBackPressed()
        }
    }



    private fun showSetServerHostDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("设置服务器地址")

        // 设置输入框
        val input = EditText(this)
        input.setHint("请输入服务器IP地址")
        input.setText(""+getServerHost())
        builder.setView(input)

        // 设置确认和取消按钮
        builder.setPositiveButton("确定") { _, _ ->
            val serverHost = input.text.toString()
            saveServerHost(serverHost)
        }
        builder.setNegativeButton("取消") { dialog, _ -> dialog.cancel() }

        builder.show()
    }

    private fun saveServerHost(serverHost: String) {
        val sharedPreferences: SharedPreferences = getSharedPreferences("HangGuangPreferences", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putString("serverHost", serverHost)
        editor.apply()
    }

    // 你可以在这里添加获取 serverHost 的方法
    fun getServerHost(): String? {
        val sharedPreferences: SharedPreferences = getSharedPreferences("HangGuangPreferences", MODE_PRIVATE)
        return sharedPreferences.getString("serverHost", "facs.healhub.cn:8000")
    }


    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        Log.i("QR扫描结果：：：","QR扫描结果：：："+requestCode)
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null && result.contents != null) {
            // 扫描成功，回调扫描结果给Activity
//            listener?.onScanResult(result.contents)

            Log.i("QR扫描结果：：：",result.contents)
            val args = bundleOf("scannedQRCodeResult" to result.contents)
            val navController = findNavController(activityMainBinding.fragmentContainer)
            navController.navigate(R.id.camera_fragment,args)
        }
    }
}